package com.wanban.player
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.media3.common.util.UnstableApi
import com.rabbit.videoplayer.MixPlayerView
import com.rabbit.videoplayer.listener.OnAdReadyLoadListener
import com.rabbit.videoplayer.listener.OnCastScreenListener
import com.rabbit.videoplayer.listener.OnChangeEpisodeListener
import com.rabbit.videoplayer.listener.OnVodCompleteListener
import com.rabbit.videoplayer.listener.OnVodErrorListener
import com.rabbit.videoplayer.response.PlayerType
import com.rabbit.videoplayer.response.VideoPlayModel
import com.wanban.adutils.AdUtils
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.utils.CommonAdTools

@UnstableApi
class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "播放器SDK"
    }

    private lateinit var btnSetting: View
    private lateinit var playerView: MixPlayerView
    private val pauseAdTools = CommonAdTools()
    private var currentPosition = 0
    // 显示投屏的dialog
    private var videoCasScreenDialog: VideoCasScreenDialog? = null

//    private val url = "https://v8.fentvoss.com/sdv8/202406/03/vDBmebRNxY14/video/index.m3u8"
    private val url = "https://v.cdnlz12.com/20240604/14961_97c9c49f/index.m3u8"


    override fun onCreate(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.BLACK
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_activity)
        btnSetting = findViewById(R.id.layout_video_setting)

        btnSetting.setOnClickListener {
            playerView.showVideoSettingDialog()
        }
        // 初始化广告
        AdUtils.initIronSource(this, "asdfasdf")



        initPlayer()

        playVideo()
    }

    private fun playVideo(){
        playerView.playVideo(
//            url,
            // 短剧
//            "https://vip.kuaikan-play1.com/20240503/eUrjun0C/index.m3u8",
            "https://play.xluuss.com/play/ZdPxxPwd/index.m3u8",
            "测试视频",
            0L,
//            currentPosition,
//            3,
            true,
            null,
            playerType = PlayerType.MEDIA3,
            false
        )
    }

    private fun initPlayer() {
        playerView = findViewById(R.id.playerView)

        playerView.setVideoModel(VideoPlayModel.NORMAL)

        playerView.setVodPreparedListener(object: com.rabbit.videoplayer.listener.player.OnPreparedListener {
            override fun onPrepared() {
                Log.e(TAG, "准备播放...onPrepared")
                playerView.start()
            }
        })

        playerView.setVodErrorListener(object : OnVodErrorListener{
            override fun onVodError(errorMsg: String?): Boolean {
                Log.e(TAG, "播放失败...onVodError")
                Log.e(TAG,"onVodError播放失败：${playerView.getCurrentPosition()}")
                return true
            }

            override fun onRetry() {
                playerView.showLoadingStatus()
                playerView.postDelayed({
                    playerView.playVideo(
                        url,
//            "https://hd.ijycnd.com/play/9addvpqLrd/index.m3u8",
                        "测试视频",
                        0L,
//                        currentPosition,
//                        3,
                        false,
                        null,
                    )
                }, 1000)

            }

        })

        playerView.setOnLoadPauseAdListener(object : OnAdReadyLoadListener {
            override fun onReady2LoadAd() {
                loadPauseAd()
            }
        })

        // 点击投屏
        playerView.setCastScreenListener(object : OnCastScreenListener {

            override fun onCastScreen() {
                playerView.onVodSuspend()
                showCastScreenBrowseDialog()
            }

            override fun onCloseCastScreen() {
                if (videoCasScreenDialog?.isShowing == true) {
                    videoCasScreenDialog?.dismiss()
                }
                videoCasScreenDialog?.disconnect()

                playerView.start()
            }

            override fun onCastScreenPlay(): Boolean {
                return videoCasScreenDialog?.startOrPauseCastScreen() ?: false
            }

            override fun seekTo(seek: Long) {
                videoCasScreenDialog?.castScreenSeekTo(seek.toInt())
            }

            override fun isStartTrackingTouch(isTouchOn: Boolean) {
                videoCasScreenDialog?.isStopUpdateCurrentPosition(isTouchOn)
            }

        })

        playerView.setVodCompleteListener(object : OnVodCompleteListener {
            override fun onVodComplete(): Boolean {
                // 默认是继续播放下一集
                return false
            }

        })

        // 播放器切换剧集监听
        playerView.setVodChangeEpisodeListener(object : OnChangeEpisodeListener {

            override fun onPlayNext(): Boolean {
                currentPosition++
                playVideo()
                return false
            }

            override fun showEpisodeList() {
            }

            override fun onPause() {
            }
        })

    }

    private fun loadPauseAd(){
        pauseAdTools.loadAd(this, AdConstants.AD_ID_VIDEO_DETAIL_PAUSE, object : OnLoadAdCallback() {
            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                playerView.hidePauseAd()
            }

            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                val rootView = playerView.showPauseAd()?:return
                pauseAdTools.showAd(rootView)
            }
        })
    }


    // 显示投屏Dialog
    private fun showCastScreenBrowseDialog() {
        if (videoCasScreenDialog == null) {
            videoCasScreenDialog = VideoCasScreenDialog(this)
            videoCasScreenDialog!!.setCastScreenCallback(object : OnCastScreenCallback {
                override fun onReadyToConnect(deviceName: String) {
                    runOnUiThread {
                        playerView.showCastScreenReadyToConnect(deviceName)
                    }
                }

                override fun onConnect() {
                    runOnUiThread {
                        playerView.showCastScreenConnected()
                    }
                }

                override fun onDisconnect(msg: String) {
                    runOnUiThread {
                        playerView.showCastScreenDisConnect(msg)
                    }
                }

                override fun onPositionUpdate(position: Long) {
                    runOnUiThread {
                        playerView.updateCastScreenCurrentPosition(position)
                    }
                }

                override fun onStart() {
                    runOnUiThread {
                        playerView.caseScreenSwitchPlayOrPause(true)
                    }
                }

                override fun onPause() {
                    runOnUiThread {
                        playerView.caseScreenSwitchPlayOrPause(false)
                    }
                }
            })
        }
        if (TextUtils.isEmpty(url)) return
        videoCasScreenDialog?.show(url, "测试视频", playerView.getCurrentPosition(), playerView.getDuration().toInt())
    }

    override fun onResume() {
        super.onResume()
        playerView.onVodResume()
    }

    override fun onPause() {
        super.onPause()
        playerView.onVodSuspend()
    }

    override fun onDestroy() {
        super.onDestroy()
        playerView.release()
    }
}

